import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useLocation, useNavigate } from 'react-router-dom';

//全局路由守卫
function RouterBeforeEach() {
    
    var navigate = useNavigate()
    var location = useLocation();
    var token = useSelector((state:any)=>state.userInfo.token);
    
    //监听路由的变化, 一旦路由发生改变, 验证token是否存在
    useEffect(()=>{
        if( !token ){ //token不存在, 跳转到登录页
            navigate('/login');
        }else if( location.pathname == '/login' ){ //token存在, 但是当前路由是'/login'
            navigate('/index');
        }
    },[location.pathname])

    return (<></>);
}

export default RouterBeforeEach;